package araxy.blog.configuration;

import araxy.blog.security.shiro.MyAuthorizationFilter;
import araxy.blog.security.shiro.MyRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfiguration {

    @Bean(name = "myRealm")
    public MyRealm myRealm() {
        return new MyRealm();
    }

    @Bean
    public DefaultWebSecurityManager securityManager(@Qualifier("myRealm") Realm realm, CookieRememberMeManager cookieRememberMeManager)
    {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(realm);
        manager.setRememberMeManager(cookieRememberMeManager); //注入rememberMeManager;
        return manager;
    }

    @Bean
    public MyAuthorizationFilter myAuthorizationFilter() {
        return new MyAuthorizationFilter();
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager,MyAuthorizationFilter myAuthorizationFilter) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/");
        shiroFilterFactoryBean.setSuccessUrl("/success");
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");

        Map<String,String> filterRules = new LinkedHashMap<>();
        filterRules.put("/login","anon");
        filterRules.put("/logout","anon");
        filterRules.put("/articles/**","anon");

        filterRules.put("/management/**","authc,roles[admin]");
        filterRules.put("/**","anon");
        Map<String, Filter> filter = new HashMap<>();
        filter.put("authc", new MyAuthorizationFilter());
        shiroFilterFactoryBean.setFilters(filter);
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterRules);

        return shiroFilterFactoryBean;
    }


    @Bean
    public SimpleCookie rememberMeCookie() {
        //cookie的名称
        SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
        //cookie生效时间30天 ,单位秒;
        simpleCookie.setMaxAge(259200);
        return simpleCookie;
    }

    //cookie管理对象;
    @Bean
    public CookieRememberMeManager cookieRememberMeManager(Cookie rememberMeCookie) {
        CookieRememberMeManager manager = new CookieRememberMeManager();
        manager.setCookie(rememberMeCookie);
        return manager;
    }

}
